
<template>
  <div 
    class="search-block" 
    :style="containerStyle"
    @click="handleClick"
  >
    <template v-if="data.navbar">
      <div 
        class="search-input-wrapper"
        :class="wrapperClasses"
      >
        <el-icon class="search-icon" :style="{ color: data.iconColor || data.fontColor }">
          <Search />
        </el-icon>
        <div class="search-input" :style="{ color: data.fontColor }">
          {{ data.placeholder }}
        </div>

        <!-- 右侧扫一扫图标 -->
        <el-icon 
          v-if="data.showScan" 
          class="scan-icon" 
          :style="{ color: data.iconColor || data.fontColor }"
          @click.stop="onScan"
        >
          <Camera />
        </el-icon>
      </div>

      <!-- 热门关键词 -->
      <div v-if="data.enableHotKeywords && data.hotKeywords && data.hotKeywords.length" class="hot-keywords">
        <el-button
          v-for="(item, index) in data.hotKeywords"
          :key="index"
          class="keyword-btn"
          :style="getKeywordStyle()"
          size="small"
          text
          @click.stop="goToSearch(item)"
        >
          {{ item }}
        </el-button>
      </div>
    </template>

    <template v-else>
      <div 
        class="input-container custom-input-container"
        :class="{ 'is-center': data.placeholderPosition === 'center' }"
        :style="{
          display: 'flex',
          justifyContent: data.placeholderPosition === 'center' ? 'center' : 'flex-start',
          width: '100%'
        }"
      >
        <div 
          class="custom-search-input"
          :class="data.placeholderPosition === 'center' ? 'justify-center' : 'justify-start'"
          :style="{
            display: 'flex',
            alignItems: 'center',
            borderRadius: data.borderRadius + 'px',
            backgroundColor: data.backgroundColor,
            width: '100%',
            padding: '0 10px',
            border: '1px solid #dcdfe6',
            transition: 'border-color 0.2s',
            height: data.height + 'px'
          }"

          @keyup.enter="onSearch"
          @clear="handleClear"
        >
          <el-icon class="search-icon" :style="{ color: data.iconColor || data.fontColor }">
            <Search />
          </el-icon>
          
          <div 
            class="search-input"
            :style="{ color: data.fontColor }"
            contenteditable="true"
            :placeholder="data.placeholder"
            @input="handleContentEditableInput"
            @keyup.enter="onSearch"
          >
            {{ searchValue }}
          </div>
          

          <el-icon 
            v-if="data.showScan" 
            :style="{ color: data.iconColor || data.fontColor }"
            class="scan-icon"
            @click="onScan"
          >
            <Camera />
          </el-icon>
          
          <el-icon
            v-if="searchValue"
            :style="{ color: data.iconColor || data.fontColor }"
            class="clear-icon"
            @click="handleClear"
          >
            <Close />
          </el-icon>
        </div>
      </div>

      <!-- 热门关键词 -->
      <div v-if="data.enableHotKeywords && data.hotKeywords && data.hotKeywords.length" class="hot-keywords">
        <span
          v-for="(item, index) in data.hotKeywords"
          :key="index"
          class="keyword-link"
          :style="getKeywordStyle()"
          @click="goToSearch(item)"
        >
          {{ item }}
        </span>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Camera } from '@element-plus/icons-vue'

// 定义组件属性
const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  styles: {
    type: Object,
    default: () => ({})
  }
})

// 定义事件
const emit = defineEmits(['update:data', 'update:styles'])

// 路由
const router = useRouter()

// 搜索值
const searchValue = ref('')

// 监听props变化，确保组件能够响应属性面板的设置
watch(() => props.data, (newVal) => {
  // 当props.data变化时，不需要额外操作，因为computed会自动更新
}, { deep: true })

watch(() => props.styles, (newVal) => {
  // 当props.styles变化时，不需要额外操作，因为computed会自动更新
}, { deep: true })

// 计算类名
const wrapperClasses = computed(() => {
  const classes = [props.data.placeholderPosition === 'center' ? 'justify-center' : 'justify-start']
  return classes
})

// 计算是否居中
const isCentered = computed(() => {
  const centered = props.data.placeholderPosition === 'center'
  return centered
})

// 计算容器样式
const containerStyle = computed(() => {
  const style = {
    minHeight: `${props.data.height}px`,
    marginTop: `${props.styles.marginTop}px`,
    marginBottom: props.data.enableHotKeywords && props.data.hotKeywords && props.data.hotKeywords.length 
      ? `${parseInt(props.styles.marginBottom) + 40}px` 
      : `${props.styles.marginBottom}px`,
    marginLeft: `${props.styles.marginLeft}px`,
    marginRight: `${props.styles.marginRight}px`
  }
  
  // 只有导航栏样式才在外层容器设置背景色和圆角
  if (props.data.navbar) {
    style.backgroundColor = props.data.backgroundColor
    style.borderRadius = `${props.data.borderRadius}px`
    style.height = `${props.data.height}px`
    // 如果有热门关键词且已启用，增加底部外边距
    if (props.data.enableHotKeywords && props.data.hotKeywords && props.data.hotKeywords.length) {
      style.marginBottom = `${parseInt(props.styles.marginBottom) + 40}px`
    }
  }
  return style
})

// 事件处理
function handleClick() {
  emit('click')
}

function onSearch() {
  // 获取contenteditable div的内容
  const searchInput = document.querySelector('.search-input')
  const value = searchInput ? searchInput.innerText : searchValue.value
  
  if (value) {
    goToSearch(value)
    // 清空搜索框
    setTimeout(() => {
      searchValue.value = ''
      if (searchInput) {
        searchInput.innerText = ''
      }
    }, 100)
  }
}

function handleClear() {
  searchValue.value = ''
  // 清空contenteditable div的内容
  const searchInput = document.querySelector('.search-input')
  if (searchInput) {
    searchInput.innerText = ''
  }
}

function handleContentEditableInput(event) {
  searchValue.value = event.target.innerText
}

// 获取关键词样式
const getKeywordStyle = () => {
  const style = {
    color: props.data.hotKeywordColor || props.data.iconColor || props.data.fontColor
  }
  
  // 设置背景色
  switch (props.data.hotKeywordStyle) {
    case 'light-gray':
      style.backgroundColor = '#f5f5f5'
      break
    case 'light-blue':
      style.backgroundColor = '#e6f7ff'
      break
    case 'light-green':
      style.backgroundColor = '#f6ffed'
      break
    case 'light-red':
      style.backgroundColor = '#fff1f0'
      break
    case 'light-yellow':
      style.backgroundColor = '#feffe6'
      break
    case 'custom':
      style.backgroundColor = props.data.hotKeywordBgColor
      break
    default:
      break
  }
  
  return style
}

function goToSearch(keyword) {
  router.push({
    path: '/goods/list',
    query: { keyword }
  })
}

function onScan() {
  // 这里可以实现扫码功能
}
</script>

<style lang="scss" scoped>
.search-block {
  width: 100%;
  box-sizing: border-box;
  padding: 0 10px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  position: relative;

  .search-input-wrapper {
    display: flex;
    align-items: center;
    width: 100%;
    height: v-bind('data.height + "px"');
    padding: 0 10px;
    background-color: v-bind('data.backgroundColor');
    border-radius: v-bind('data.borderRadius + "px"');
    transition: all 0.3s ease;
    box-sizing: border-box;

    &.justify-center {
      justify-content: center;
      
      .search-input {
        flex: none;
        text-align: center;
      }
    }

    &.justify-start {
      justify-content: flex-start;
    }

    .search-icon {
      font-size: 18px;
      margin-right: 8px;
    }

    .search-input {
      flex: 1;
      font-size: 14px;
    }

    .scan-icon {
      font-size: 18px;
      margin-left: 8px;
      cursor: pointer;
    }
  }

  .hot-keywords {
    margin-top: 8px;
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    box-sizing: border-box;
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 10;
    background-color: transparent;
    padding: 8px 10px;

    .keyword-btn {
      margin-right: 10px;
      margin-bottom: 5px;
      padding: 2px 8px;
      border-radius: 4px;
    }

    .keyword-link {
      margin-right: 15px;
      margin-bottom: 5px;
      font-size: 12px;
      cursor: pointer;
      padding: 2px 8px;
      border-radius: 4px;
      display: inline-block;

      &:hover {
        text-decoration: underline;
      }
    }
  }
  
  // 输入框容器样式
  .input-container {
    width: 100%;
    display: flex;
    
    &.is-center {
      justify-content: center;
      
      .el-input {
        width: auto;
        min-width: 200px;
        max-width: 100%;
      }
    }
  }
  
  // 自定义输入框容器样式
  .custom-input-container {
    width: 100%;
    box-sizing: border-box;
    &.is-center {
      justify-content: center;
      
      .custom-search-input {
        justify-content: center;
        width: auto;
        max-width: 100%;
      }
    }
  }
  
  // 自定义搜索输入框样式
  .custom-search-input {
    display: flex;
    align-items: center;
    
    .search-icon {
      font-size: 18px;
      margin-right: 8px;
    }
    
    .search-input {
      flex: 1;
      font-size: 14px;
      outline: none;
      border: none;
      background: transparent;
      height: 100%;
      display: flex;
      align-items: center;
      
      &:empty:before {
        content: attr(placeholder);
        color: v-bind('data.fontColor');
        opacity: 0.6;
      }
    }
    
    .scan-icon, .clear-icon {
      font-size: 18px;
      margin-left: 8px;
      cursor: pointer;
    }
    
    &.justify-center {
      justify-content: center;
      
      .search-input {
        flex: none;
        text-align: center;
        min-width: 100px;
        max-width: 100%;
      }
    }
    
    &.justify-start {
      justify-content: flex-start;
    }
  }
  
  // 输入框样式
  :deep(.el-input) {
    width: 100%;
    
    // 使用Element Plus的CSS变量
    --el-input-text-color: v-bind('data.fontColor');
    --el-input-placeholder-color: v-bind('data.fontColor');
    --el-input-icon-color: v-bind('data.iconColor || data.fontColor');
    
    .el-input__wrapper {
      background-color: v-bind('data.backgroundColor') !important;
      border-radius: v-bind('data.borderRadius + "px"') !important;
      display: flex;
      align-items: center;
    }
    
    // 设置文字颜色
    .el-input__inner {
      color: var(--el-input-text-color) !important;
      text-align: v-bind('data.placeholderPosition === "center" ? "center" : "left"') !important;
      flex: 1;
    }
    
    // 设置图标颜色
    .el-input__prefix, .el-input__suffix {
      .el-icon {
        color: var(--el-input-icon-color) !important;
      }
    }
    
    // 确保占位符颜色正确
    input::placeholder {
      color: var(--el-input-placeholder-color) !important;
      opacity: 0.6;
    }
    
    // 居中时的特殊样式
    &[style*="text-align: center"] .el-input__wrapper {
      justify-content: center;
      
      .el-input__inner {
        text-align: center !important;
      }
    }
  }
  
  // 居中时的特殊样式
  .input-container.is-center {
    :deep(.el-input) {
      width: auto;
      min-width: 200px;
      
      .el-input__wrapper {
        justify-content: center !important;
        padding: 0 12px;
        
        .el-input__inner {
          text-align: center !important;
        }
        
        .el-input__prefix,
        .el-input__suffix {
          position: static !important;
          margin: 0 8px;
        }
      }
    }
  }
}
</style>
